package elicecn.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
	/**
	 * 根据特定参数获取连接数据
	 * 
	 * @return
	 * @throws IOException
	 */
	public static String[] getJdbcProperties() throws IOException {
		return getJdbcProperties("/conf/jdbc.properties", "driverClass",
				"jdbcUrl", "user", "password");
	}

	/**
	 * 根据指定参数获取连接数据
	 * 
	 * @param url
	 * @param driverClassName
	 * @param jdbcUrlName
	 * @param userName
	 * @param passwordName
	 * @return
	 * @throws IOException
	 */
	public static String[] getJdbcProperties(String url,
			String driverClassName, String jdbcUrlName, String userName,
			String passwordName) throws IOException {
		Properties prop = new Properties();
		prop.load(JdbcUtils.class.getResourceAsStream(url));
		String driverClass = prop.getProperty("driverClass");
		String jdbcUrl = prop.getProperty("jdbcUrl");
		String user = prop.getProperty("user");
		String password = prop.getProperty("password");
		return new String[] { driverClass, jdbcUrl, user, password };
	}

	/**
	 * 获取连接
	 * 
	 * @param driverClass
	 * @param url
	 * @param user
	 * @param password
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getConnection(String driverClass, String url,
			String user, String password) throws ClassNotFoundException,
			SQLException {
		Class.forName(driverClass);
		return DriverManager.getConnection(url, user, password);
	}

	/**
	 * 根据配置获取连接
	 * 
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getConnectionByJdbcConfig() throws IOException,
			ClassNotFoundException, SQLException {
		String[] param = getJdbcProperties();
		return getConnection(param[0], param[1], param[2], param[3]);
	}
}
